using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;

namespace Umdf.SideShow.Contents
{
    public class ImageContent : Content
    {
        private Image _image;
        private ImageFormat _format;

        public ImageContent(BinaryReader reader)
        {
            DeserializeObject(reader);
        }

        public ImageContent(uint id, Image image) : base(id)
        {
            _image = new Bitmap(image);
            _format = image.RawFormat;
        }

        public Image Image
        {
            get { return _image; }
        }

        public override void Save(string dir)
        {
            string ext = "png"; // "unknownimage";
            foreach (ImageCodecInfo enc in ImageCodecInfo.GetImageEncoders())
            {
                if (enc.FormatID == _format.Guid)
                {
                    string[] parts = enc.FilenameExtension.Split(';');
                    ext = parts[0].Substring(2).ToLower();
                }
            }

            string filename = Path.Combine(dir, Id.ToString() + "." + ext);
            _image.Save(filename);
        }

        protected internal override void DeserializeObject(BinaryReader reader)
        {
            base.DeserializeObject(reader);
            byte[] buf = reader.ReadBytes(16);
            Guid f = new Guid(buf);
            _format = new ImageFormat(f);
            int l = reader.ReadInt32();
            buf = reader.ReadBytes(l);
            using (MemoryStream ms = new MemoryStream(buf))
            {
                _image = new Bitmap(ms);
            }
        }

        protected internal override void SerializeObject(BinaryWriter writer)
        {
            base.SerializeObject(writer);
            writer.Write(_format.Guid.ToByteArray());
            using (MemoryStream ms = new MemoryStream())
            {
                _image.Save(ms, _format);
                byte[] buf = ms.ToArray();
                writer.Write(buf.Length);
                writer.Write(buf);
            }
        }
    }
}
